<template>
    <div class="role-container">
        <!-- 面包导航 -->
        <el-breadcrumb separator="/" style="padding-left: 10px; padding-bottom: 10px; font-size: 12px">
            <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>系统管理</el-breadcrumb-item>
            <el-breadcrumb-item>角色管理</el-breadcrumb-item>
        </el-breadcrumb>
        <!-- 主体区域 -->
        <el-card class="box-card">
            <!-- 搜素区域 -->
            <el-row :gutter="20">
                <el-col :span="8">
                    <el-input
                        clearable
                        size="small"
                        placeholder="请输入角色名查询"
                        v-model="queryMap.roleName"
                        class="input-with-select"
                        @clear="getRoleList"
                    >
                        <el-button slot="append" icon="el-icon-search" @click="search"></el-button>
                    </el-input>
                </el-col>
                <el-col :span="4">
                    <el-button
                        size="small"
                        v-hasPermission="'role:add'"
                        type="success"
                        icon="el-icon-circle-plus-outline"
                        @click="addDialogVisible = true"
                        >添加</el-button
                    >
                    <el-button size="small" v-hasPermission="'role:export'" icon="el-icon-download" @click="downExcel"
                        >导出</el-button
                    >
                </el-col>
            </el-row>

            <!--    角色表格区域    -->
            <el-table
                v-loading="loading"
                :data="roleData"
                border
                style="width: 100%; margin-top: 20px"
                height="470"
                size="small"
            >
                <el-table-column prop="id" label="ID" width="100"></el-table-column>
                <el-table-column prop="roleName" label="角色名" width="180"></el-table-column>
                <el-table-column prop="createTime" label="创建时间" width="150"></el-table-column>
                <el-table-column prop="status" label="是否禁用" width="100">
                    <template slot-scope="scope">
                        <el-switch v-model="scope.row.status" @change="changRoleStatus(scope.row)"></el-switch>
                    </template>
                </el-table-column>
                <el-table-column prop="remark" sortable label="备注" width="420"></el-table-column>
                <el-table-column fixed="right" label="操作" width="280" center>
                    <template slot-scope="scope">
                        <el-button @click="grant(scope.row.id)" type="warning" icon="el-icon-present" size="mini"
                            >授权</el-button
                        >
                        <el-button
                            @click="edit(scope.row.id)"
                            v-hasPermission="'role:edit'"
                            icon="el-icon-edit-outline"
                            size="mini"
                            >编辑</el-button
                        >
                        <el-button
                            v-hasPermission="'role:delete'"
                            @click="del(scope.row.id)"
                            type="danger"
                            icon="el-icon-delete"
                            size="mini"
                            >删除</el-button
                        >
                    </template>
                </el-table-column>
            </el-table>

            <!-- 分页区域 -->
            <div class="pagination-container" style="margin: 10px 0; float: right">
                <el-pagination
                    background
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                    :current-page="queryMap.pageNum"
                    :page-sizes="[8, 16, 32, 64]"
                    :page-size="queryMap.pageSize"
                    layout="total, sizes, prev, pager, next, jumper"
                    :total="total"
                ></el-pagination>
            </div>
        </el-card>

        <!-- 添加角色对话框 -->
        <el-dialog title="添加角色" :visible.sync="addDialogVisible" width="35%" @close="closeAdd">
            <el-form ref="addFormRef" :model="addForm" label-width="80px" :rules="FormRoles">
                <el-form-item label="角色名称" prop="roleName">
                    <el-input v-model="addForm.roleName"></el-input>
                </el-form-item>
                <el-form-item label="描述信息" prop="remark">
                    <el-input type="textarea" v-model="addForm.remark"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer">
                <el-button @click="addDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="addRole">添 加</el-button>
            </span>
        </el-dialog>

        <!-- 编辑角色对话框 -->
        <el-dialog title="编辑角色" :visible.sync="editDialogVisible" width="35%" @close="closeEdit">
            <el-form ref="editFormRef" :model="editForm" label-width="80px" :rules="FormRoles">
                <el-form-item label="角色名称" prop="roleName">
                    <el-input v-model="editForm.roleName"></el-input>
                </el-form-item>
                <el-form-item label="描述信息" prop="remark">
                    <el-input type="textarea" v-model="editForm.remark"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer">
                <el-button @click="editDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="editRole">编 辑</el-button>
            </span>
        </el-dialog>

        <!-- 角色授权对话框 -->
        <el-dialog title="分配菜单权限" :visible.sync="grantDialogVisible" width="38%">
            <span>
                <el-tree
                    :auto-expand-parent="false"
                    :data="data"
                    show-checkbox
                    node-key="id"
                    :default-expanded-keys="open"
                    :props="defaultProps"
                    ref="tree"
                    highlight-current
                ></el-tree>
            </span>
            <span slot="footer" class="dialog-footer">
                <el-button @click="grantDialogVisible = false">取 消</el-button>
                <el-button
                    v-hasPermission="'role:authority'"
                    type="primary"
                    :loading="btnLoading"
                    icon="el-icon-setting"
                    @click="authority"
                    >授 权</el-button
                >
            </span>
        </el-dialog>
    </div>
</template>

<script>
import axios from "axios";
export default {
    name: "Role",

    data() {
        return {
            queryMap: { roleName: "", pageNum: 1, pageSize: 8 }, //查询条件
            addDialogVisible: false, //显示添加对话框
            editDialogVisible: false, //编辑对话框
            grantDialogVisible: false, //授权对话框
            loading: false,
            total: 0,
            grantId: null, //需要授权的id
            roleData: [
                { id: "1", roleName: "物资运输员", createTime: "2021-12-09", status: true, remark: "测试备注一下" },
            ], //角色表格数据
            addForm: {}, //添加数据
            editForm: {}, //编辑数据

            FormRoles: {
                roleName: [
                    { required: true, message: "请输入角色名称", trigger: "blur" },
                    { min: 3, max: 10, message: "长度在 3 到 10 个字符", trigger: "blur" },
                ],
                remark: [
                    { required: true, message: "请输入角色描述信息", trigger: "blur" },
                    { min: 5, max: 20, message: "长度在 5 到 20 个字符", trigger: "blur" },
                ],
            }, //添加验证规则

            btnLoading: false,
            data: [], //菜单数据
            open: [], //默认打开节点的key集合
            defaultProps: {
                children: "children",
                label: "menuName",
            }, //基础变量配置
        };
    },
    created() {
        this.loading = true;
        this.getRoleList();
        setTimeout(() => {
            this.loading = false;
        }, 500);
    },

    mounted() {},

    methods: {
        // 1. 加载角色列表
        async getRoleList() {
            const { data: res } = await this.$http.get("role/findRoleList", { params: this.queryMap });
            // console.log(res);
            if (res.code == 200) {
                this.roleData = res.data.rows;
                this.total = res.data.total;
            } else {
                return this.$message.error("获取角色列表失败!");
            }
        },

        // 2. 搜索
        search() {
            this.pageNum = 1;
            this.getRoleList();
        },

        // 导出Excel
        downExcel() {
            const that = this;
            const res = axios
                .request({
                    url: "role/excel",
                    method: "post",
                    responseType: "blob",
                })
                .then((res) => {
                    if (res.headers["content-type"] === "application/json") {
                        return that.$message.error("Subject does not have permission [role:export]");
                    }
                    const data = res.data;
                    let url = window.URL.createObjectURL(data); // 将二进制文件转化为可访问的url
                    const a = document.createElement("a");
                    document.body.appendChild(a);
                    a.href = url;
                    a.download = "角色列表.xls";
                    a.click();
                    window.URL.revokeObjectURL(url);
                });
        },

        //改变角色禁用状态
        async changRoleStatus(row) {
            // console.log(row);// console.log("row", row.status);
            const { data: res } = await this.$http.put("role/updateStatus/" + row.id + "/" + row.status);
            if (res.code == 200) {
                const message = row.status ? "角色状态已禁用" : "角色状态已启用";
                this.$notify.success({
                    title: "操作成功",
                    message: message,
                });
            } else {
                this.$message.error("更新角色状态失败!");
                row.status = !row.status;
            }
        },

        // 授权
        async grant(id) {
            // 获取菜单树
            const { data: res } = await this.$http.get("role/findRoleMenu/" + id);
            // console.log(res);
            if (res.code == 200) {
                //默认选中的树的数据
                setTimeout(() => {
                    res.data.mids.forEach((value) => {
                        this.$refs.tree.setChecked(value, true, false);
                    });
                }, 100);
                this.data = res.data.tree;
                this.open = res.data.open;
                this.grantId = id; //需要授权的id
            } else {
                return this.$message.error("获取角色列表失败!");
            }
            this.grantDialogVisible = true;
        },

        // 编辑
        async edit(id) {
            const { data: res } = await this.$http.get("role/edit/" + id);
            if (res.code == 200) {
                // 角色数据回显
                this.editForm = res.data;
                this.editDialogVisible = true;
            } else {
                return this.$message.error("角色信息编辑失败!");
            }
        },

        // 删除
        del(id) {
            this.$confirm("此操作将永久删除该角色, 是否继续?", "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning",
            })
                .then(async () => {
                    const { data: res } = await this.$http.delete("role/delete/" + id);
                    // console.log(res);
                    if (res.code == 200) {
                        this.$message({
                            type: "success",
                            message: "删除成功!",
                        });
                        this.getRoleList();
                    }
                })
                .catch(() => {
                    this.$message({
                        type: "info",
                        message: "已取消删除",
                    });
                });
        },

        // 关闭添加对话框
        closeAdd() {
            this.addDialogVisible = false;
            this.$refs.addFormRef.resetFields(); // 清空上次的校验
        },
        // 关闭编辑对话框
        closeEdit() {
            this.editDialogVisible = false;
            this.$refs.editFormRef.resetFields(); // 清空上次的校验
        },

        // 添加角色
        addRole() {
            this.$refs.addFormRef.validate(async (valid) => {
                if (valid) {
                    const { data: res } = await this.$http.post("role/add", this.addForm);
                    // console.log(res);
                    if (res.code == 200) {
                        this.$notify.success({
                            title: "操作成功",
                            message: "角色添加成功",
                        });
                        this.addForm = {};
                        this.addDialogVisible = false;
                        this.getRoleList();
                    }
                } else {
                    return this.$message.error("角色添加失败!");
                }
            });
        },
        // 编辑角色
        editRole() {
            this.$refs.editFormRef.validate(async (valid) => {
                if (valid) {
                    const { data: res } = await this.$http.put("role/update/" + this.editForm.id, this.editForm);
                    if (res.code == 200) {
                        this.$notify({
                            title: "操作成功",
                            message: "角色基本信息已更新",
                            type: "success",
                        });
                        this.editForm = {};
                        this.getRoleList();
                        this.editDialogVisible = false;
                    }
                } else {
                    return this.$message.error("角色信息更新失败!");
                }
            });
        },

        // 获取选中的节点
        async authority() {
            this.btnLoading = true;
            const { data: res } = await this.$http.post(
                "role/authority/" + this.grantId,
                [].concat(this.$refs.tree.getCheckedKeys(), this.$refs.tree.getHalfCheckedKeys())
                // concat拼接两个数组返回一个新数组
            );
            if (res.code == 200) {
                this.$message.success("角色授权成功");
                this.grantDialogVisible = false;
            } else {
                this.$message.error("角色授权失败");
            }
            this.btnLoading = false;
        },
        //改变页码
        handleSizeChange(newSize) {
            this.queryMap.pageSize = newSize;
            this.getRoleList();
        },
        //翻页
        handleCurrentChange(current) {
            this.queryMap.pageNum = current;
            this.getRoleList();
        },
    },
};
</script>

<style lang="less" scoped></style>
